package edu.upc.cineplanet.repositoryjdbc;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

import edu.upc.cineplanet.Domain.Cine;
import edu.upc.cineplanet.repository.CineRepository;


@Repository
public class CineRepositoryJdbc extends JdbcDaoSupport implements CineRepository {

	@Autowired
	public CineRepositoryJdbc(DataSource dataSource){
		setDataSource(dataSource);
	}
		
	public List<Cine> obtenerCines() {
		
		List<Cine> cines = new ArrayList<Cine>();
		
		String sql = "SELECT * FROM CINE";
		cines = getJdbcTemplate().query(sql, new CineRowMapper());
		
		return cines;
	}	
	
	private class CineRowMapper implements ParameterizedRowMapper<Cine>{		
		public Cine mapRow(ResultSet rs, int rowNum) throws SQLException{
			Cine p = new Cine();
			p.setCodigoCine(rs.getString("CO_CINE"));
			p.setNombreCine(rs.getString("NO_CINE"));
			p.setDireccionCine(rs.getString("NO_DIRECCION"));
			p.setTelefonoCine(rs.getString("NO_TELEFONO"));
			p.setFotoCine(rs.getString("FOTOCINE"));
			
			return p;		
		}		
	}
	
	public Cine buscarCine(String Codigo){
		String sql = "SELECT * FROM CINE WHERE CO_CINE=?";
		Cine cine;
		try{
			cine = getJdbcTemplate().queryForObject(sql, new Object[]{Codigo}, new CineRowMapper());			
		}catch(EmptyResultDataAccessException ex){
			return null;
		}
		return cine;
	}	
	
	public String mostrarCines(){
		String lista="";		
		int registro=1;
		Iterator<Cine> itr = obtenerCines().iterator();		
		while (itr.hasNext()){
		    Cine usua = itr.next();
		    lista = lista + registro+ " " + usua.getCodigoCine()+" "+ usua.getNombreCine() +" "+ usua.getDireccionCine() +" "+ usua.getTelefonoCine()  + "\n" ;
		    registro++;
		}		
		return lista;
	}	
		
	public String creaCodigo(Cine usu) {
		String codigo;
		String nuevo_codigo;
		String sql = "SELECT (MAX(U.CO_CINE)+1) FROM CINE U";
		codigo = getJdbcTemplate().queryForObject(sql, String.class);
		
		nuevo_codigo = codigo;
		int tam = 0,diff = 0;
		if(codigo.length() < 2){
			tam = codigo.length();	
			diff = 2-tam;
			while(diff>0){
				nuevo_codigo = "0"+nuevo_codigo ;
				diff--;
			}						
		}
		return nuevo_codigo;
	}
	
}
